package com.fangmou.ing.publish.freemarker.directive;

import java.io.IOException;
import java.util.Map;

import com.fangmou.ing.publish.freemarker.DirectiveUtils;
import com.fangmou.ing.publish.freemarker.DirectiveBodyWraper;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 父级block引用命令
 * 无name指定时需同override联合使用，延用override的name
 * @可选参数：name（对应父模板中block名称）
 * @author kongdy
 */
public class SuperDirective implements TemplateDirectiveModel {

  public void execute(Environment env, Map params, TemplateModel[] loopVars,
      TemplateDirectiveBody body) throws TemplateException, IOException {

    String name = DirectiveUtils.getParam(params, "name", null);
    if (name != null) {
      //super占位符，待解析完整个模板后填充
      env.getConfiguration().setCustomAttribute(DirectiveUtils.getSuperPlaceholder(name), name);
      env.getOut().write(DirectiveUtils.getSuperPlaceholder(name));
    } else {
      DirectiveBodyWraper current = (DirectiveBodyWraper) env.getVariable(DirectiveUtils.OVERRIDE_CURRENT_NODE);
      if (current == null) {
        throw new TemplateException("<@_super /> direction must be child of _override", env);
      }
      TemplateDirectiveBody parent = current.parentBody;
      if (parent == null) {
        throw new TemplateException("not found parent for <@_super />", env);
      }
      parent.render(env.getOut());
    }

  }
}



